/**
 * Created by IntelliJ IDEA.
 *
 * @Avatar: xyb
 * Date: 2017/8/2
 * Time: 18:01
 * To change this template use File | Settings | File Templates.
 */

package blog.web.setting;

import blog.sys.entity.User;
import blog.sys.service.SettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import pub.spring.web.mvc.ActionResult;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: xyb
 * @Time: 18:01
 * @Version: 2017/8/2
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class MainController {

    /**
     * 获取用户信息到帐户与安全页面
     *
     * @param userId
     * @return
     */
    @RequestMapping
    public ActionResult onShowUserInfoSafe(Integer userId) {
        User user = settingService.onShowUserInfoSafeService(userId);
        ActionResult result = ActionResult.ok();
        result.setData(user);
        return result;
    }

    /**
     * 保存用户头像
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping
    public ActionResult onUpdateAvatarFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

        ActionResult result = ActionResult.ok();
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        String fileName = file.getOriginalFilename();
        BASE64Encoder encoder = new BASE64Encoder();
        // 通过base64来转化图片
        String data = encoder.encode(file.getBytes());
//        System.out.println(data);
        String strUserId = multipartRequest.getParameter("userId");
        String strAvatar = multipartRequest.getParameter("avatar");
        Integer userId = null;
        Integer avatar = null;
        if (strUserId != "null") {
            userId = Integer.parseInt(strUserId);
        }
        if (!strAvatar.equals("null")) {
            avatar = Integer.parseInt(strAvatar);
        }

        settingService.onUpdateAvatarFileService(fileName, userId, avatar, data);

        return result;
    }

    @Autowired
    private SettingService settingService;
}
